<template>
  <com-form>
    <el-form :model="ruleForm" ref="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm">
      <el-form-item label="工单一级类型:" prop="yjType">
        <el-select v-model="ruleForm.yjType" placeholder="请选择一级类型" popper-class="kxz-callLog__sel" @change="handleChangeYJ">
          <el-option v-for="(item,index) in Pque1" :key="index" :label="item.name" :value="item.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工单二级类型:" prop="ejType">
        <el-select v-model="ruleForm.ejType" placeholder="请选择二级类型" popper-class="kxz-callLog__sel" @change="handleChangeEJ">
          <el-option v-for="(item,index) in Pque2" :key="index" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工单标题:" prop="title">
        <el-input v-model="ruleForm.title"></el-input>
      </el-form-item>
      <el-form-item label="紧急程度:" prop="degree">
        <el-select v-model="ruleForm.degree" placeholder="请选择紧急程度" popper-class="kxz-callLog__sel">
          <el-option v-for="item in opts.degreeList" :key="item.id" :label="item.text" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="客户姓名:" prop="uname">
        <el-input v-model="ruleForm.uname"></el-input>
      </el-form-item>
      <el-form-item label="客户id:">
        <el-input v-model="ruleForm.uid"></el-input>
      </el-form-item>
      <el-form-item label="客户电话:" prop="tel">
        <el-input v-model="ruleForm.tel"></el-input>
      </el-form-item>
      <el-form-item label="VIP等级:" prop="vip">
        <el-input v-model="ruleForm.vip"></el-input>
      </el-form-item>
      <el-form-item label="渠道选项:" prop="src">
        <el-input v-model="ruleForm.src"></el-input>
      </el-form-item>
      <el-form-item label="使用端口:" prop="port">
        <el-select v-model="ruleForm.port" placeholder="请选择紧急程度" popper-class="kxz-callLog__sel">
          <el-option v-for="item in opts.portList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="问题描述:" prop="desc">
        <el-input type="textarea" v-model="ruleForm.desc" placeholder="请输入问题描述" class="desc"></el-input>
      </el-form-item>
      <el-form-item label="解决进度:" prop="progress">
        <el-input type="textarea" v-model="ruleForm.progress" placeholder="请输入进度描述" class="desc"></el-input>
      </el-form-item>
      <!-- <el-form-item label="期望处理时间:" prop="expectTime">
        <el-date-picker
          v-model="ruleForm.expectTime"
          type="datetime"
          placeholder="选择日期时间"
        >
        </el-date-picker>
      </el-form-item> -->
      <el-form-item label="上传附件:">
        <el-upload :action="postUrl" ref="uploadBill" accept="image/*" :multiple="false" :auto-upload="false">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且只能选择一个文件</div>
        </el-upload>
      </el-form-item>
      <p class="submitPara">
        <el-button type="primary" class="submitBtn" @click="handleSubmit">提交</el-button>
      </p>
    </el-form>
  </com-form>
</template>

<script>
import ComForm from '../../../../../components/comTable'
import {dateFormat}  from 'vux'

// 必须通过全局变量才能使得datepicker中disabledDate来获取
let callCreatedTime

export default {
  name: 'dialog6',
  props:{
    Pque1:Array,
    Pque2:Array,
    Pselque1: String,
    Pselque2: Number,
  },
  data() {
    const {telMsg, mobile} = this.$store.getters.callMsg
    let { cName, id ,VipLevel, qdname} = telMsg
    VipLevel = VipLevel!== '' || VipLevel !== undefined ? parseInt(VipLevel) : VipLevel
    const checkPhone = (rule, value, callback) => {
      if (!value) {
          return callback(new Error('手机号不能为空'));
        }
        setTimeout(() => {
          if (new RegExp('^0?((13[0-9])|(15[^,\\D])|(17[0-9])|(147)|(18[0-9]))\\d{8}$').test(value) === false) {
            return callback(new Error('请输入正确的手机号码'));
          }
        }, 1000);
    }
    const checkIsNil = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('选项不能为空'))
      }
    }
    const checkIsVip = (rule, value, callback) => {
      if (Number.isNaN(Number(value))) {
        return callback(new Error('请填写数字'))
      }
    }
    const yjType = this.Pselque1
    const ejType = this.Pselque2 || ''
    return {
      // postUrl: 'http://report.wsloan.com:8888/workorder/workorderout/addworkorder1.do',
      postUrl: 'http://192.168.31.151:8080/workorder/workorderout/addworkorder1.do',  // upload组件必须给action一个url
      ruleForm: {
        yjType,
        ejType,
        title: '',
        degree: 2,
        uname: cName,
        uid: id,
        tel: mobile,
        vip: VipLevel || 0 ,
        src: qdname  || '无',
        port: 'ios',
        desc: '',
        progress: '',
        expectTime: Date.now(),
      },
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < (callCreatedTime + 30 * 60 * 1000)
        }
      },
      opts: {
        ejList: [],
        degreeList: [],
        portList:['ios','安卓','PC']
      },
      rules: {
        yjType:[
          {type:'string', required: true, message: '请选择一级类型', trigger: 'change'},
        ],
        ejType:[
          {type:'number', required: true, message: '请选择二级类型', trigger: 'change'}
        ],
        title: [
          { required: true, message: '请输入工单标题', trigger: 'blur' }
        ],
        degree:[
          {type:'number', required: true, message: '请选择紧急程度', trigger: 'change'}
        ],
        uname: [
          { required: true, message: '请输入客户姓名', trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkIsNil, trigger: 'blur' }
        ],
        vip:[
          // { required: true, message: '请输入vip等级', trigger: 'blur' },
          { validator: checkIsVip, trigger: 'blur' }
        ],
        // src:[
        //   { required: true, message: '请输入渠道名称', trigger: 'blur' }
        // ],
        // port:[
        //   { required: true, message: '请输入使用端口', trigger: 'blur' }
        // ],
        desc: [
          { required: true, message: '请输入描述', trigger: 'blur' }
        ],
        progress: [
          { required: true, message: '请输入解决进度', trigger: 'blur' }
        ],
      }
    }
  },
  computed: {
    cuForm() {
      const { id } = this.$store.getters.getUserInfo
      const { title, ejType, degree, uname, tel, desc, expectTime, uid, progress, vip, src, port} = this.ruleForm
      const {curRecordFile} = this.$store.getters.callMsg
      return {
        userid: id,
        title,
        twoType: ejType,
        flg: degree,
        customername: uname,
        customerphone: tel,
        context: desc,
        expecttime: dateFormat(expectTime,'YYYY-MM-DD HH:mm:ss'),
        customerid: uid || '',
        contextProgress: progress,
        audioURL:`http://report.wsloan.com:8888/telrecord/main/listentovoice?date=/media/sda/voice/${curRecordFile}.wav`,
        // 新增
        viplevel:vip,
        qdname:src,
        syport:port,
      }
    }
  },
  watch: {
    Pselque1(val){
      this.ruleForm.yjType = val
    },
    Pselque2(val){
      this.ruleForm.ejType = val || ''
    },
  },
  components: {
    ComForm
  },
  mounted() {
    // 获取degreeList
    this.getDegreeList()
    callCreatedTime = this.$store.getters.callMsg.createdTime || Date.now()
    this.expectTime = callCreatedTime + 30 * 60 * 1000
  },
  methods: {
    handleChangeYJ(val) {
      this.$emit('onSelQue1', val)
    },
    handleChangeEJ(val) {
      this.$emit('onSelQue2', val)
    },
    handleSubmit() {
        //能够提交工单说明已经进入通话
        const ruleForm = this.$refs.ruleForm
        const {title, uname, desc, progress, vip, src, port} = this.ruleForm
        let flag = true
        ruleForm.validate((valid) => {
          if (!valid){
            flag = false
            return false
          }
        })
        /***
         *   应急处理
         */
        if(title === ''){
          this.$warn('请填写工单标题')
          return
        }
        if(uname === ''){
          this.$warn('请填写客户姓名')
          return
        }
        if (Number.isNaN(Number(vip))) {
          this.$warn('请填写数字')
          return
        }
        //
        // if(src === ''){
        //   this.$warn('请填写渠道名称')
        //   return
        // }
        // if(port === ''){
        //   this.$warn('请填写使用端口')
        //   return
        // }
        //
        if(desc === ''){
          this.$warn('请填写问题描述')
          return
        }
        if(progress === ''){
          this.$warn('请填写解决进度')
          return
        }
        const files = this.$refs.uploadBill.uploadFiles
        if(files.length > 1){
          this.$warn('只可上传一个文件')
          return
        }
        if(flag){
          this.postForm()
        }
    },
    async getDegreeList() {
      const api = 'showFlg.do'
      const url = 'http://report.wsloan.com:8888/workorderapi/'
      try {
        const { data } = await this.$get(this, {
          api
        }, url)
        this.opts.degreeList = data
      } catch (e) {
        this.$warn(`系统${api}接口报错`)
      }
    },
    async postForm(){
      const url = 'http://report.wsloan.com:8888/workorderapi/workorderout/addworkorder1.do'
      // const url = 'http://192.168.3.26:6026/workorderout/addworkorder1.do'
      try{
        const formData = new FormData()
        const files = this.$refs.uploadBill.uploadFiles
        const {userid,
                title,
                twoType,
                flg,
                customername,
                customerphone,
                context,
                expecttime,
                customerid,
                contextProgress,
                audioURL,
                viplevel,
                qdname,
                syport} = this.cuForm
        // 添加提交参数
        if(files.length > 0){
          formData.append('userfile', files[0]['raw'])
        }
        formData.append('userid', userid)
        formData.append('title', title)
        formData.append('twoType', twoType)
        formData.append('flg', flg)
        formData.append('customername', customername)
        formData.append('customerphone', customerphone)
        formData.append('context', context)
        formData.append('expecttime', expecttime)
        formData.append('customerid', customerid)
        formData.append('contextProgress', contextProgress)
        formData.append('audioURL', audioURL)
        //
        // 增加参数
        formData.append('viplevel', viplevel || 0)
        formData.append('qdname', qdname || '无')
        formData.append('syport', syport || '无')
        //
        const res = await fetch(url, {
          method:'post',
          mode:'cors',
          body:formData
        })
        const ret = await res.json()
        if(ret.code === 0 && ret.content === 1){
          // this.$emit('onCloseDialog', '转工单完成')
          this.$store.dispatch('updateDialog', {
            isSwitch: false,
            isSubmitGD: true
          })
          this.$toast({
             message: '提交工单成功'
          })
          return
        }
        this.$warn('提交工单不成功')
      }catch(e){
        this.$warn(`系统${url}接口报错`)
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.el-select {
  display: inline;
}

.submitPara {
  text-align: center;
  .submitBtn {
    padding: 12px 60px;
  }
}
</style>
